// Copyright (C) 2020-2022 Intel Corporation
//
// SPDX-License-Identifier: MIT

import React, { ReactNode, useEffect, useRef, useState } from 'react';
import { Button, Drawer, Modal, Tooltip, Image } from 'antd/lib';
import { ActionType, ProColumns, ProFormInstance, ProProvider, ProTable } from '@ant-design/pro-components';
import { DatePicker, message, ConfigProvider } from 'antd';
import { Moment } from 'moment';
import CreateTaskComponent from '../create-task/create-task';
import BatchUploadComponent from '../batch-upload/batch-upload';
import { deleteImage, getDataList, getImageMarkStates, getUploadUserList } from 'apis/database';
import { PlusOutlined, SearchOutlined, SmileOutlined } from '@ant-design/icons';
import { ResetIcon } from 'icons';
import AuthPerm from 'components/common/AuthPerm';

enum MarkStateTypeEnum {
    Unlabeled = 0, // 未标注
    Labeling = 1, // 标注中
    Labeled = 2, // 已标注
    UnusedData = 3, // 无效数据
}

const stateColorMapping = {
    0: '#000',
    1: '#165DFF',
    2: '#00B42A',
    3: '#F53F3F',
};

interface DataItemType {
    key?: React.Key;
    id: string;
    imageName: string;
    imageUrl: string;
    imageStatus: MarkStateTypeEnum;
    createUserName: string;
    createTime: string;
    completeTime: string;
}

function DataBasePageComponent(): JSX.Element {
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [selectedRows, setSelectedRows] = useState<DataItemType[]>([]);
    const [pageInfo, setPageInfo] = useState({ pageIndex: 1, pageSize: 20, total: 0 });
    const { RangePicker } = DatePicker;
    const [refresh, setRefresh] = useState(false); // 是否需要更新list

    const getMarkStateOption = async () => {
        const res = await getImageMarkStates({});
        return res.statusList.map((v) => {
            return {
                label: v.imageStatusName,
                value: v.imageStatus
            };
        })
    }

    const fetchUploadUserList = async () => {
        const res = await getUploadUserList({});
        return res.userList.map(v => {
            return { label: v.userName, value: v.userId };
        })

    }

    const disabledDate = (date: Moment) => {
        const curDate = new Date().getTime();
        // 这里设置天数，这里为30天内可选
        const numMonth = 30 * 24 * 3600 * 1000;
        const threeMonths = curDate - numMonth;
        return new Date(date).getTime() > curDate || new Date(date).getTime() < threeMonths;
    };

    const columns: ProColumns<DataItemType>[] = [
        {
            title: '数据ID',
            dataIndex: 'id',
            sorter: true,
            key: 'id',
            valueType: 'text',
            search: true,
            order: 4,
        },
        { title: '数据名称', dataIndex: 'imageName', sorter: true, key: 'imageName', valueType: 'text', search: true, order: 3 },
        {
            title: '图片',
            dataIndex: 'imageUrl',
            sorter: false,
            search: false,
            valueType: 'image',
            key: 'imageUrl',
            render: (text, record) => (
                <Image
                    width={48}
                    height={48}
                    src={record.imageUrl}

                />
            ),
        },
        {
            title: '标注状态',
            dataIndex: 'imageStatus',
            key: 'imageStatus',
            sorter: true,
            order: 6,
            search: true,
            valueType: 'select',
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择标注状态',
            },
            request: async () => {
                return getMarkStateOption();
            },
            render: (text: ReactNode, record, index: number, action) => [
                (<span
                    className='flex flex-items-center'
                    style={{ color: stateColorMapping[record.imageStatus] }}
                >
                    <i style={{
                        display: 'inline-block',
                        marginRight: '6px',
                        width: '4px',
                        height: '4px',
                        borderRadius: '2px',
                        backgroundColor: stateColorMapping[record.imageStatus],
                    }}
                    />
                    {text}
                </span>),
            ],
        },
        {
            title: '上传人',
            dataIndex: 'createUserName',
            key: 'createUserName',
            sorter: true,
            search: true,
            order: 5,
            valueType: 'select',
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择上传人',
            },
            request: async () => {
                return fetchUploadUserList();
            }
        },
        {
            title: '上传时间',
            dataIndex: 'createTime',
            key: 'createTime',
            sorter: true,
            valueType: 'dateTime',
            search: true,
            order: 2,
            fieldProps: {
                disabledDate: disabledDate,
            },
            renderFormItem: (item, { type, defaultRender, ...rest }, form) => (
                <RangePicker
                    showTime={false}
                    placeholder={['开始日期', '结束日期']}
                    format='YYYY-MM-DD HH:mm:ss'
                />
            ),
        },
        {
            title: '完成标注时间',
            dataIndex: 'completeTime',
            key: 'completeTime',
            sorter: true,
            valueType: 'dateTime',
            search: true,
            order: 1,
            renderFormItem: (item, { type, defaultRender, ...rest }, form) => (
                <RangePicker
                    showTime={false}
                    placeholder={['开始日期', '结束日期']}
                    format='YYYY-MM-DD HH:mm:ss'
                />
            ),
        },
        {
            title: '操作',
            dataIndex: 'handler',
            sorter: false,
            key: 'handler',
            valueType: 'option',
            search: false,
            fixed: 'right',
            render: (text, record, _, action) => [
                (record.imageStatus === MarkStateTypeEnum.Unlabeled || record.imageStatus === MarkStateTypeEnum.UnusedData) ?

                    <ConfigProvider
                        theme={{
                            components: {
                                Button: {
                                    paddingInline: 0,
                                }

                            }
                        }}
                    >
                        <AuthPerm permission='delete'>
                            <Button
                                type='link'
                                size='middle'
                                onClick={() => {
                                    const modal = Modal.confirm({});
                                    modal.update({
                                        title: '删除',
                                        content: '删除后不可恢复，请确认是否删除数据？',
                                        closable: false,
                                        okText: '确定删除',
                                        onOk: () => {
                                            deleteItem(record);
                                            modal.destroy();
                                        },
                                        onCancel: () => {
                                            modal.destroy();
                                        },
                                        cancelText: '取消',
                                    });
                                }}
                            >
                                删除
                            </Button>
                        </AuthPerm>

                    </ConfigProvider>
                    :
                    <span className='text-#1677ff'>--</span>
                ,
            ],
        },
    ];

    const pageSizeOptions = [10, 20, 50, 100];
    const [showDrawer, setShowDrawer] = useState(false); // 显示隐藏创建任务modal
    const [showUpload, setShowUpload] = useState(false);
    const [showCreateTask, setShowCreateTask] = useState(false);

    function search(): void {
        formRef.current.submit();
        tableRef.current.reload();
        setSelectedRows([]);
    }

    function clear(): void {
        formRef.current?.resetFields();
        search();
    }

    async function deleteItem(record: DataItemType): Promise<void> {
        await deleteImage({
            ids: record.id
        });
        setPageInfo({
            ...pageInfo,
            pageIndex: 1,
        });
        tableRef.current?.reload();
        message.success('删除成功！')
        search();
    }

    async function batchDeleteData(): Promise<void> {
        await deleteImage({
            ids: selectedRows.map(v => v.id).join(',')
        })
        setPageInfo({
            ...pageInfo,
            pageIndex: 1,
        });
        tableRef.current?.reload();
        message.success('批量删除成功！')
        search();
    }

    function refreshList(): void {
        if (refresh) {
            tableRef.current?.reload();
        }
    }

    return (
        <>
            <ProTable<DataItemType>
                actionRef={tableRef}
                formRef={formRef}
                columns={columns}
                tableClassName='database-table'
                request={async (
                    params,
                    sort,
                    filter,) => {
                    const { imageStatus = [], imageName, id, createUserName = [], createTime = [], completeTime = [] } = params;
                    const [createTimeStart, createTimeEnd] = createTime;
                    const [completeTimeStart, completeTimeEnd] = completeTime;
                    let sortKey;
                    let sortType;
                    Object.keys(sort).forEach(v => {
                        sortKey = v;
                        sortType = sort[v];
                    })
                    const sortAscColumn = sortType === 'ascend' ? sortKey : ''; //升序字段
                    const sortDescColumn = sortType === 'descend' ? sortKey : '';
                    try {
                        const r = await getDataList({
                            pageIndex: params.current,
                            pageSize: params.pageSize,
                            imageStatus,
                            imageName,
                            id,
                            createUserIds: createUserName,
                            createTimeStart,
                            createTimeEnd,
                            completeTimeStart,
                            completeTimeEnd,
                            sortAscColumn,
                            sortDescColumn
                        });
                        const arr = r ? (r?.DataList).map(v => {
                            return {
                                key: v.id,
                                id: v.id,
                                imageName: v.imageName,
                                imageUrl: v.imageUrl,
                                imageStatus: v.imageStatus,
                                createUserName: v.createUserName,
                                createTime: v.createTime,
                                completeTime: v.completeTime,
                            };
                        }) : [];
                        return {
                            data: arr,
                            success: true,
                            total: r ? r.total : 0,
                        };
                    } catch (error) {
                        return {
                            data: [],
                            success: true,
                            total: 0,
                        };
                    }

                }}
                scroll={{ y: 'calc(100vh - 400px)', x: '100%' }}
                pagination={{
                    pageSize: pageInfo.pageSize,
                    current: pageInfo.pageIndex,
                    total: pageInfo.total,
                    pageSizeOptions,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total}条`,
                    onChange: (page, pageSize) => {
                        setPageInfo({
                            ...pageInfo,
                            pageIndex: page,
                        });
                    },
                }}
                search={{
                    defaultCollapsed: false,
                    collapseRender: false,
                    searchText: '查询',
                    labelWidth: 'auto',
                    className: 'search-wrapper',
                    optionRender: () => [
                        <Button key='clear' icon={<ResetIcon />} onClick={() => clear()}>重置</Button>,
                        <Button key='search' type='primary' icon={<SearchOutlined />} onClick={() => search()}>查询</Button>,
                    ],
                }}
                rowSelection={{
                    alwaysShowAlert: false,
                    onChange: (selectedKeys, selectedRowsArr) => {
                        setSelectedRows(selectedRowsArr);
                    },
                }}
                tableAlertRender={false}
                options={{
                    density: false,
                    setting: false,
                    reload: false,
                }}
                toolbar={{
                    title: (
                        <AuthPerm permission='createTask'>
                            <Tooltip title='勾选「未标注」数据，可创建任务'>
                                <Button
                                    key='createTask'
                                    type='primary'
                                    disabled={!(selectedRows.length
                                        && selectedRows.every((v) => v.imageStatus === MarkStateTypeEnum.Unlabeled))}
                                    icon={<PlusOutlined />}
                                    onClick={() => {
                                        setShowDrawer(true);
                                        setShowUpload(false);
                                        setShowCreateTask(true);
                                    }}
                                >
                                    创建任务
                                </Button>
                            </Tooltip>
                        </AuthPerm>
                    ),

                }}
                toolBarRender={() => [
                    <AuthPerm permission='batchDelete'>
                        <Tooltip title='勾选「未标注」或「无效数据」数据，可批量删除'>
                            <Button
                                key='batchDelete'
                                disabled={!(selectedRows.length
                                    && selectedRows.every((v) => v.imageStatus === MarkStateTypeEnum.Unlabeled
                                        || v.imageStatus === MarkStateTypeEnum.UnusedData))}
                                onClick={() => {
                                    const modal = Modal.confirm({});
                                    modal.update({
                                        title: '批量删除',
                                        content: `删除后不可恢复，请确认是否删除${selectedRows.length}条数据？`,
                                        closable: false,
                                        okText: '确定删除',
                                        onOk: () => {
                                            batchDeleteData();
                                            modal.destroy();
                                        },
                                        onCancel: () => {
                                            modal.destroy();
                                        },
                                        cancelText: '取消',
                                    });
                                }}
                            >
                                批量删除
                            </Button>
                        </Tooltip>
                    </AuthPerm>,
                    <AuthPerm permission='importData'>
                        <Button
                            key='importBtn'
                            onClick={() => {
                                setShowDrawer(true);
                                setShowUpload(true);
                                setShowCreateTask(false);
                            }}
                        >
                            批量导入
                        </Button>
                    </AuthPerm>,
                ]}
            />
            <Drawer
                title={showUpload ? '批量导入' : '创建任务批次'}
                placement='right'
                destroyOnClose={true}
                width='max(33%, 640px)'
                styles={{
                    body: { padding: 0 },
                }}
                onClose={() => {
                    setShowDrawer(false);
                    refreshList();
                }}
                open={showDrawer}
            >
                {showUpload && (<BatchUploadComponent onAddNewData={() => setRefresh(true)} closeDrawer={() => {
                    setShowDrawer(false);
                    refreshList();
                }} />)}
                {showCreateTask && (<CreateTaskComponent max={1} selectedRows={selectedRows} onAddNewTask={() => {
                    setShowDrawer(false);
                    tableRef.current?.reload();
                }} closeDrawer={() => {
                    setShowDrawer(false);
                }} />)}
            </Drawer>
        </>
    );
}

export default React.memo(DataBasePageComponent);
